package com.travel.controller;

import com.travel.exception.BigException;
import com.travel.util.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionResolver {

	//统一处理异常
	@ResponseBody
	@ExceptionHandler(value={RuntimeException.class})
	public ResponseEntity catchException(RuntimeException ex){
		//记录日志 记录一般日志
		System.out.println("一般日志:" + ex.getMessage());
		ResponseEntity responseEntity = new ResponseEntity();
		responseEntity.setSuccess(false);
		responseEntity.setMessage(ex.getMessage());
		return responseEntity;
	}


	//统一处理异常
	@ResponseBody
	@ExceptionHandler(value={BigException.class})
	public ResponseEntity catchBigException(BigException ex){
		//记录日志 记录严重日志
		System.out.println("严重日志:" + ex.getMessage());
		ResponseEntity responseEntity = new ResponseEntity();
		responseEntity.setSuccess(false);
		responseEntity.setMessage(ex.getMessage());
		return responseEntity;
	}

	@ResponseBody
	@ExceptionHandler(value = BindException.class)
    public ResponseEntity validExceptionHandler(BindException e) {
		ResponseEntity responseEntity = new ResponseEntity();
		responseEntity.setSuccess(false);
		responseEntity.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return responseEntity;
    }
}
